<?php
namespace app\api\controller\project;

use think\Controller;

class Project extends Controller{

    public function __construct()
    {
        parent::__construct();

        $this->ProjectModel = Model('Project.Project');
        $this->OrderModel = Model('Project.Order');
        $this->UserModel = model('User.User');
        $this->RecordModel = model('User.Record');
        $this->AddressModel = model('User.Address');

    }

    // 添加预约
    public function add()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0 );
            $addrid = $this->request->param('addrid', 0);
            $projectid = $this->request->param('projectid', 0);
            $createtime = $this->request->param('createtime', '');
            $content = $this->request->param('content','');

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            //用户的收货地址
            $address = $this->AddressModel->find($addrid);

            if(!$address){
                $this->error('收货地址不存在');
                exit;
            }

            //判断这个收货地址是不是这个用户的
            if($address['userid'] != $userid)
            {
                $this->error('非法选择上门地址');
                exit;
            }

            //判断服务选项是否存在
            $project = $this->ProjectModel->find($projectid);

            if(!$project){
                $this->error('预约的服务不存在，请重新选择');
                exit;
            }

            //将毫秒转换为秒
            $createtime = $createtime / 1000;

            //判断是否是否为过期的时间
            $now = time() + 3600 * 6;
            if($now > $createtime)
            {
                 $this->error('请选择有效时间，在当前时间的6个小时后预约');
                 exit;
            }

            $data =[
                'userid' =>$userid,
                'addrid' => $addrid,
                'projectid' => $projectid,
                'content' => $content,
                'status' => 0,
                'createtime' => $createtime
            ];

            $result = $this->OrderModel->validate('common/Project/Order')->save($data);
 
            if($result === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }else
            {
                $this->success('预约成功，请等待客服联系', '/pages/project/index');
                exit;
            }
        }
    }

    // 预约列表
    public function index()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0 );
            $status = $this->request->param('status', '');

            $where = [];
            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            $where['userid'] = $userid;

            if($status == '0' || !empty($status)){
                $where['status'] = $status;
            }
            $result = $this->OrderModel->where($where)->select();
          

            if($result === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }else
            {
                $this->success('','', $result);
                exit;
            }
        }
    }

    // 支付
    public function pay()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0 );
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if(!$orderinfo){
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            if($orderinfo['status'] != '1')
            {
                $this->error('预约已经付款，不需要重复付款');
                exit;
            }

            $point = $userinfo['point'];

            // 判断用户积分够不够
            $UpdatePoint = bcsub($point, $orderinfo['price']);

            if($UpdatePoint < 0 ){

                $this->error('积分不足，请充值后操作');
                exit;
            }

            // 开启事条
            //预约订单表(update) 用户积分(update) 消费记录(insert)
            $this->OrderModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            //组装订单表数据
            $orderdata = [
                'id' => $id,
                'status' => 2
            ];

            //预约订单表
            $OrderStatus = $this->OrderModel->isUpdate()->save($orderdata);

            
            if($OrderStatus === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }

            // 用户积分
            $UserStatus = $this->UserModel->isUpdate()->save(['id' => $userid, 'point' => $UpdatePoint]);

            if($UserStatus === FALSE)
            {
                //回滚
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 消费记录
            $RecordData = [
                'point' => $orderinfo['price'],
                'content' => "预约订单的---消费的积分为：".$orderinfo['price'],
                'state' => 6,
                'userid' => $userid
            ];
            // 插入消费记录表
            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if($RecordStatus === FALSE)
            {
                //回滚
                $this->UserModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if($OrderStatus !== FALSE &&  $UserStatus !== FALSE && $RecordStatus !== FALSE)
            {
                //提交事务
                $this->OrderModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->success('付款成功');
                exit;
            }else
            {
                //回滚
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->OrderModel->rollback();
                $this->error('付款失败,请重新操作');
                exit;
            }
        }
    }

    // 撤销
    public function revoke()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0 );
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if(!$orderinfo){
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            $data = [
                'id' => $id,
                'status' => -1
            ];

            //预约订单表
            $result = $this->OrderModel->isUpdate()->save($data);

            if($result === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }else
            {
                $this->success('撤销预约订单成功，请等待后台审核','', null);
                exit;
            }
        }
    }

    // 详情
    public function info()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0 );
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if(!$orderinfo){
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            
            //预约订单详情
            $result = $this->OrderModel->with('project')->where(['order.id' => $id])->find();

           
            if($result === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }else
            {
                $this->success('','', $result);
                exit;
            }
        }
    }

    // 评分
    public function rate()
    {
        if($this->request->isPost())
        {
            $userid = $this->request->param('userid', 0 );
            $id = $this->request->param('id', 0);
            $rate = $this->request->param('rate', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if(!$orderinfo){
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            $data = [
                'id' => $id,
                'rate' => $rate
            ];

            //评分
            $result = $this->OrderModel->isUpdate()->save($data);

           
            if($result === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }else
            {
                $this->success('预约订单评价成功','', '');
                exit;
            }
        }
    }

    // 消费记录
    public function records(){
        if($this->request->isPost()){
            $userid = $this->request->param('userid',0);
            // 判断用户是否存在
            $userinfo = $this->UserModel->find($userid);
            if(!$userinfo){
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'userid' => $userid,
                'status' => ['in',[2,3,-1]]
            ];
            $records = $this->OrderModel->with('project')->where($where)->select();
            foreach($records as $item) {
                $item->price = $item->status == -1 ? +$item->price : -$item->price;
            }
            if(!$records){
                $this->error('暂无消费记录');
                exit;
            }else{
                $this->success('ok',null,$records);
            }
        }
    }
}
